package com.mogician.qrrelay.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mogician.qrrelay.R;
import com.mogician.qrrelay.util.PermissionUtil;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;
import com.yzq.zxinglibrary.encode.CodeCreator;

public class MainActivity extends AppCompatActivity
{
    public final static int REQUEST_CODE_SCAN = 3;
    public final static int REQUEST_CODE_GRADE = 4;
    private final static String seperation = ",";
    private boolean graded = false;
    private int random;
    private int grade;
    private String content;

    ImageView imageView;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);
        textView = (TextView) findViewById(R.id.textView);

        ImageButton scanBtn = (ImageButton) findViewById(R.id.btn_scan);
        scanBtn.setOnClickListener(v->
        {
            if(PermissionUtil.requestPermission(MainActivity.this,
                    new String[]{
                            Manifest.permission.CAMERA,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                    }, 1))
            {
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
            }
        });

        Button restartBtn = (Button) findViewById(R.id.btn_restart);
        restartBtn.setOnClickListener(v->
        {
            content = "0,0,0";
            Intent intent = new Intent(MainActivity.this, GradeActivity.class);
            startActivityForResult(intent, REQUEST_CODE_GRADE);
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults)
    {
        switch (requestCode)
        {
            case 1:
                if(PermissionUtil.allGranted(MainActivity.this, grantResults))
                {
                    Intent intent = new Intent(MainActivity.this,
                            CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode)
        {
            case REQUEST_CODE_SCAN:
                // 扫描二维码/条码回传
                if (resultCode == RESULT_OK)
                {
                    if (data != null)
                    {
                        content = data.getStringExtra(Constant.CODED_CONTENT);
                        if(!graded)
                        {
                            Intent intent = new Intent(MainActivity.this,
                                    GradeActivity.class);
                            startActivityForResult(intent, REQUEST_CODE_GRADE);
                        }
                        else
                        {
                            graded = false;//重置
                            int[] num = parse(content);
                            num[0] -= random;
                            num[2]++;
                            content = num[0] + seperation
                                    + num[1] + seperation + num[2];
                            generateQR();
                            if(num[1] == num[2])
                            {
                                //可以显示平均分
                                textView.setText("平均分:"
                                        + String.format("%.2f", num[0]/(double)num[1])
                                        + "\n第一轮参与人数：" + num[1]
                                        + "\n第二轮参与人数：" + num[1]);
                            }
                            else
                                textView.setText("评分中\n第一轮参与人数：" + num[1]
                                                    + "\n第二轮参与人数：" + num[2]);
                        }
                    }
                }
                break;
            case REQUEST_CODE_GRADE:
                if(resultCode == RESULT_OK)
                {
                    graded = true;
                    grade = data.getIntExtra("grade", 5);
                    int[] num = parse(content);
                    random = (int)(Math.random() * 10);
                    content = grade + random + num[0] + seperation
                            + (num[1] + 1) + seperation + num[2];
                    textView.setText("评分中\n第一轮参与人数：" + (num[1] + 1)
                                        + "\n第二轮参与人数：" + num[2]);
                    generateQR();
                }
                break;
            default:
        }
    }

    private void generateQR()
    {
        Bitmap bitmap = CodeCreator.createQRCode(content, 200, 200, null);
        imageView.setImageBitmap(bitmap);
        Toast.makeText(MainActivity.this, "已生成新的二维码", Toast.LENGTH_SHORT)
            .show();
    }

    private int[] parse(String content)
    {
        String[] tmp = content.split(seperation);
        int[] num = new int[3];
        for(int i = 0; i < 3; i++)
            num[i] = Integer.parseInt(tmp[i]);
        return num;
    }

}
